package lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 想要设计出可以被中断的锁，就用lockInterruptibly方法
 * 本代码比较了lock和lockInterruptibly方法
 * @author lcx
 *
 */
public class LockInterruptiblyTest {

	public static void main(String[] args) throws InterruptedException {
		ReentrantLock lock=new ReentrantLock();
		LockInterruptiblyThread td1=new LockInterruptiblyThread(lock);
		LockInterruptiblyThread td2=new LockInterruptiblyThread(lock);
		td1.start();
		td2.start();
		//此时，我想中断td2线程
//		Thread.sleep(2000);
		td2.interrupt();
	}

}

class LockInterruptiblyThread extends Thread
{
	ReentrantLock lock;
	public LockInterruptiblyThread(ReentrantLock lock)
	{
		this.lock=lock;
	}

	@Override
	public void run()
	{
		try {
			lock.lockInterruptibly();
//			lock.lock();
			System.out.println("start......");
			Thread.sleep(1000);
			lock.unlock();
			System.out.println("end");
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			System.out.println("中断线程了！！！");
			e1.printStackTrace();
		}
	}
}
